﻿using BootstrapBlazor.Components;
using BootstrapBlazorApp.Shared.Client;
using BootstrapBlazorApp.Shared.Data;
using BootstrapBlazorApp.Shared.Models;
using BootstrapBlazorApp.Shared.Models.POMain;
using BootstrapBlazorApp.Shared.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Json;

namespace BootstrapBlazorApp.Shared.Pages.POMain
{
    public partial class List
    {

        private static readonly
          ConcurrentDictionary<Type, Func<IEnumerable<POInfoListModel>, string, SortOrder, IEnumerable<POInfoListModel>>>
          SortLambdaCache = new();

        [Inject]
        [NotNull]
        private PODemandClient poDemandClient { get; set; }


        [Inject]
        [NotNull]
        private VaccinationPointClient vaccinationPointClient { get; set; }

        [Inject]
        [NotNull]
        private VaccineClient vaccineClient { get; set; }

        private List<SelectedItem> CompanyList { get; set; }
        private List<SelectedItem> VaccinationPointList { get; set; }
        private List<SelectedItem> VaccineList { get; set; }


        private POInfoListModel SearchModel { get; set; } = new POInfoListModel();

        private static IEnumerable<int> PageItemsSource => new int[] { 20, 50, 100 };

        private List<POInfoListModel>? Items { get; set; } = new List<POInfoListModel>();

        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override async Task OnInitializedAsync()
        {
            var vaccineList = await vaccineClient.GetAllListAsync();
            VaccineList = vaccineList?.Select(x => new SelectedItem { Value = x.Id.ToString(), Text = x.Code }).ToList();

            await this.PagingAsync();




           
            //var vaccineDataList = await vaccineClient.GetAllListAsync();
            //VaccineList = vaccineDataList?.Select(x => new SelectedItem {  Value = x.Id.ToString(),Text =x.Name }).ToList();

        }

        private static Task<POInfoListModel> OnAddAsync() =>
            Task.FromResult(new POInfoListModel());

        /// <summary>
        /// 保存站点信息
        /// </summary>
        /// <param name="item"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        private async Task<bool> OnSaveAsync(POInfoListModel item, ItemChangedType changedType)
        {
            if (changedType == ItemChangedType.Add)
            {
                await this.CreateAsync(item);
            }
            else
            {
                await this.UpdateAsync(item);
            }

            await this.PagingAsync();

            return true;
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<POInfoListModel> items)
        {
            var keyIds = items.Select(item => item.Id).ToArray();
            foreach (var id in keyIds)
            {
                await this.RemoveAsync(id);
            }

            await this.PagingAsync();

            return true;
        }

        private static Task OnResetSearchAsync(POInfoListModel item)
        {
            item.CompanyName = "";
            item.VaccinationPointName = "";
            return Task.CompletedTask;
        }

        private Task<QueryData<POInfoListModel>> OnQueryAsync(QueryPageOptions options)
        {
            IEnumerable<POInfoListModel> items = Items;

            // 处理高级搜索
            if (!string.IsNullOrEmpty(SearchModel.CompanyName))
            {
                items = items.Where(item =>
                    item.CompanyName?.Contains(SearchModel.CompanyName, StringComparison.OrdinalIgnoreCase) ?? false);
            }

            if (!string.IsNullOrEmpty(SearchModel.CompanyName))
            {
                //items = items.Where(item => item.)?.Contains(SearchModel.), StringComparison.OrdinalIgnoreCase) ?? false);
            }

            // 处理 Searchable=true 列与 SeachText 模糊搜索
            if (options.Searchs.Any())
            {
                items = items.Where(options.Searchs.GetFilterFunc<POInfoListModel>(FilterLogic.Or));
            }
            else
            {
                // 处理 SearchText 模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    items = items.Where(item => (item.CompanyName?.Contains(options.SearchText) ?? false)
                                                || (item.VaccineName?.Contains(options.SearchText) ?? false));
                }
            }

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<POInfoListModel>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                //var invoker = SortLambdaCache.GetOrAdd(typeof(UserTableModel), key => LambdaExtensions.GetSortLambda<UserTableModel>().Compile());
                //items = invoker(items, options.SortName, options.SortOrder);
                isSorted = true;
            }

            // 设置记录总数
            var total = items.Count();

            // 内存分页
            items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<POInfoListModel>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = !string.IsNullOrEmpty(SearchModel.CompanyName) || !string.IsNullOrEmpty(SearchModel.VaccineName)
            });
        }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        private async Task OnRowButtonClick(POInfoListModel item)
        {
            var cate = ToastCategory.Success;
            var title = "行内按钮处理方法";
            var content = "通过不同的函数区分按钮处理逻辑，参数 Item 为当前行数据";
            await ToastService.Show(new ToastOption()
            {
                Category = cate,
                Title = title,
                Content = content
            });
        }

        #region Service服务调用

        /// <summary>
        /// 添加需求信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task CreateAsync(POInfoListModel item)
        {

            Random rd = new Random();
            int rowIndex = rd.Next();


            await poDemandClient.CreateAsync(new POMainModel
            {
                Code = "PO" + DateTime.Now.ToString("yyyyMMddHHmmsss") + rowIndex.ToString(),
                DemandDate = item.DemandDate,
                //ManufactorId =item.ManufactorId,
                //VaccinationPointId = item.VaccinationPointId,
                Items =new List<PODetailsModel> {
                    new PODetailsModel{
                        POMainId = item.POMainId,
                        Quantity = item.Quantity,
                        VaccineId = item.VaccineId
                    }
                }

            });

        }

        /// <summary>
        /// 加载需求列表
        /// </summary>
        /// <returns></returns>
        public async Task PagingAsync()
        {
            var result = await poDemandClient.GetPagedPOInfoAsync();

            Items = result?.Items?.ToList();
        }

        /// <summary>
        /// 删除需求
        /// </summary>
        /// <param name="keyIds"></param>
        public async Task RemoveAsync(Guid id)
        {
            await poDemandClient.DeleteItemAsync(id);
        }

        /// <summary>
        /// 更新需求信息
        /// </summary>
        /// <param name="item"></param>
        public async Task UpdateAsync(POInfoListModel item)
        {
            var editModel = new POMainModel
            {
                Code = item.Code,
                DemandDate = item.DemandDate,
                ManufactorId = item.ManufactorId,
                VaccinationPointId = item.VaccinationPointId,
                Items = new List<PODetailsModel> {
                    new PODetailsModel{
                        POMainId = item.POMainId,
                        Quantity = item.Quantity,
                        VaccineId = item.VaccineId
                    }
                }

            };
            await poDemandClient.UpdateAsync(item.POMainId, editModel);
        }

        #endregion
    }
}
